#include "stdafx.h"
#include "base/thread/MessagePump.h"

namespace xBase
{
    CxMessagePump::CxMessagePump()
        : m_pState(NULL)
        , m_nHaveWork(0)
    {}

    CxMessagePump::~CxMessagePump()
    {}

    VOID CxMessagePump::RunWithDispatcher(IxDelegate* pDelegate, IxDispatcher* pDispatcher)
    {
        CxRunState state;
        state.m_pDelegate = pDelegate;
        state.m_pDispatcher = pDispatcher;
        state.m_bShouldQuit = FALSE;
        state.m_nRunDepth = m_pState ? (m_pState->m_nRunDepth + 1) : 1;

        CxRunState* pPrevState = m_pState;
        m_pState = &state;

        DoRunLoop();

        m_pState = pPrevState;
    }

    VOID CxMessagePump::Quit()
    {
        m_pState->m_bShouldQuit = TRUE;
    }

    INT CxMessagePump::GetCurrentDelay() const
    {
        if (m_oDelayedWorkTime.IsNull())
            return -1;

        DOUBLE dbTimeOut = ceil((m_oDelayedWorkTime - xBase::CTime::Now()).InMillisecondsF());

        INT nDelay = static_cast<INT>(dbTimeOut);

        if (nDelay < 0)
            nDelay = 0;

        return nDelay;
    }
}